package com.ryujung.dfs_backtracking;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

class Solution216 {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> stk = new ArrayDeque<>();
        dfs(k, n, 1, 0, stk, res);
        return res;
    }

    private void dfs(int k, int n, int curNum, int sum,
                     Deque<Integer> stk, List<List<Integer>> res) {
        if (stk.size() == k) {
            if (sum == n) {
                res.add(new ArrayList<>(stk));
            }
            return;
        }
        if (sum > n) {
            return;
        }
        // 需要 k-stk.size   还有 9-i+1个
        // k-stk.size<=9-i+1
        for (int i = curNum; i <= 9 + 1 - (k - stk.size()); i++) {
            stk.addLast(i);
            dfs(k, n, i + 1, sum + i, stk, res);
            stk.removeLast();
        }
    }
}